<script setup>
import {
    Position,
    Handle,
    useVueFlow
} from '@vue-flow/core'
import {
    watch, inject, ref, nextTick, onMounted
} from "vue";

const props = defineProps(['id', 'data'])
const flow = useVueFlow();
const updateNodesData = inject("updateNodesData")
import {
    getNodeOutputFieldNames
} from '../node-def'

// 监听props.data的变化
watch(() => props.data, (newValue, oldValue) => {
    console.log('props.data changed ', newValue);
    updateNodesData();
}, {
    deep: true
})

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = ref([{
    label: "自定义内容",
    value: "jb_custom"
}])


watch(() => flow.getEdges.value, (newV) => {
    console.debug("监听到edge改动", newV)
    updatePrevOutputFieldOptions(props.id);
})
//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV) => {
    //如果数组是空值,则清空input的值
    if (newV.length === 0) {
        props.data.outputToClientConfig.inputField = null;
        //清空输入框
    }
    //默认追加一个自定义的问题
    prevOutputFieldOptions.value.push({
        label: "自定义内容",
        value: "jb_custom"
    });

})
flow.onEdgesChange(events => {
    console.debug("intention init", events)
    if (events.some(item => item.type === 'remove' || item.type === 'add')) {
        prevOutputFieldOptions.value = [];
        insertQuestionOptions.value = []
        updatePrevOutputFieldOptions(props.id);
    }
})


function updatePrevOutputFieldOptions(sourceNodeId) {
    const connections = flow.getConnectedEdges(sourceNodeId).filter(edge => edge.targetNode.id == sourceNodeId);
    console.debug(connections, "connections")
    // 遍历所有前置连接
    connections.forEach(connection => {
        const sourceNode = connection.sourceNode;
        if (sourceNode) {
            // 获取该类型节点的所有输出字段名称
            const outputFields = getNodeOutputFieldNames(sourceNode.type);
            // 从sourceNode.data中获取对应字段的值
            outputFields.forEach(fieldPath => {
                // 处理嵌套字段路径，如 "llmConfig.outputField"
                const value = fieldPath.split('.').reduce((obj, key) => obj && obj[key], sourceNode
                    .data);
                if (value) {
                    if (prevOutputFieldOptions.value.some(item => item.value === value) == false) {
                        prevOutputFieldOptions.value.unshift({
                            label: value,
                            value: value
                        });
                        insertQuestionOptions.value.unshift({
                            label: value,
                            value: value
                        })
                    }
                }
            });
            console.log(prevOutputFieldOptions.value, "Ai的llmConfig的意图是被数组")
            updatePrevOutputFieldOptions(connection.source)
        }
    });
}


/** 获取所有前置节点的输出字段，并生成下拉选项 */

/**动态插入变量-----------------------------*/
//变量数组
const insertQuestionOptions = ref([])
const textarea = ref(null);
const insertValue = ref('')

//选中值,就在光标的指定位置插入值
watch(() => insertValue.value, (newV) => {
    if (newV != "") {
        insertText('${' + newV + '}');
    }
    insertValue.value = '';
})
// 在指定位置插入变量
const insertText = (insertText) => {
    // 确保textarea元素存在
    if (!textarea.value) return;

    // 初始化inputTpl，防止null或undefined的情况
    if (!props.data.outputToClientConfig.inputTpl) {
        props.data.outputToClientConfig.inputTpl = '';
    }

    // 获取光标起始位置和结束位置
    const startPos = textarea.value.selectionStart;
    const endPos = textarea.value.selectionEnd;

    // 插入文本到光标位置后
    const beforeText = props.data.outputToClientConfig.inputTpl.substring(0, startPos);
    const afterText = props.data.outputToClientConfig.inputTpl.substring(endPos, props.data.outputToClientConfig.inputTpl.length);

    // 更新textarea的值
    props.data.outputToClientConfig.inputTpl = beforeText + insertText + afterText;

    // 更新光标位置
    nextTick(() => {
        textarea.value.focus();
        textarea.value.setSelectionRange(startPos + insertText.length, startPos + insertText.length);
    });
};
/**动态插入变量-----------------------------*/


</script>

<template>
    <div class="_container">
        <div class="fx fx-c_center pad-16 header">
            <div class="fx fx-center wh-40 logo">
                <jb-icon :local="true" icon="jam:phone" width="30" color="#2e8ded"></jb-icon>
            </div>
            <div class="ml-10 tc-dark">
                <div>输出到客户端</div>
                <p class="font-12 tc-assist">输出内容到客户端</p>
            </div>
        </div>
        <div class=" fx-col pad-16 ">

            <div>
                <div class="mt-8 mb-8 fx fx-m_between">
                    <label>是否将AI回答保存到数据库</label>
                    <n-switch v-model:value="props.data.outputToClientConfig.persistDb"/>
                </div>
            </div>
            <n-form-item label="内容来源">
                <n-select placeholder="请选择内容来源" clearable v-model:value="props.data.outputToClientConfig.inputField"
                          :options="prevOutputFieldOptions"></n-select>
            </n-form-item>
            <div v-if="props.data.outputToClientConfig.inputField === 'jb_custom'" @mousedown.stop @wheel.stop>
                <div class="flex justify-between mb-1.5">
                    <label>自定义内容</label>
                    <n-popselect
                        v-model:value="insertValue"
                        :options="insertQuestionOptions"
                        size="medium"
                        scrollable
                    >
                        <n-button strong secondary type="success" size="tiny">
                            <jb-icon :local="true" icon="jam:plus-circle"></jb-icon>
                            插入变量
                        </n-button>
                    </n-popselect>
                </div>
                <textarea v-model="props.data.outputToClientConfig.inputTpl" type="textarea" ref="textarea"
                          placeholder="请输入自定义内容，可以通过插入变量动态生成内容" :rows="8"
                ></textarea>
            </div>
        </div>

        <Handle type="target" :position="Position.Left"/>


    </div>
</template>

<style scoped>
._container {
    background-color: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-sizing: border-box;
    width: 380px;
    box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px;
}

.header,
.form {
    border-bottom: 1px solid rgb(229, 231, 235);
}

.logo {
    background: #5822d926;
    border-radius: 12px;
}

label {
    margin-bottom: 8px;
}

label:not(:first-child) {
    margin-top: 16px;
}

textarea {
    width: 100%;
    border-radius: 3px;
    border: 1px solid #bfbfc2;
    padding: 5px;
    /* scrollbar-width: none; 控制滚动条的宽度：auto | thin | none */
}

textarea:focus {
    border: 1px solid #18a058 !important;
    outline: none;
}

</style>
